package com.cumt.util.init;

import com.cumt.framework.config.ConfigHelper;
import com.cumt.init.InitSys;
import com.cumt.util.DateUtil;
import com.cumt.websocket.config.WsEndpointConfig;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.websocket.jsr356.server.ServerContainer;
import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer;

import javax.servlet.ServletException;
import javax.websocket.DeploymentException;


public class StartJetty {

    private static StartJetty sj = null;

    private static boolean status = false;

    private StartJetty() {
    }

    public static StartJetty getInstance() {
        if (sj == null) {
            sj = new StartJetty();
        }
        return sj;
    }

    public static boolean getStatus() {
        return status;
    }

    public void startJetty() {
        InitSys.init();   //初始化系统的配置
        Logger log = LogManager.getLogger(StartJetty.class);
        String rootPath = StartJetty.class.getResource("/").getFile().toString();
        rootPath = rootPath.replace("target/classes/", ConfigHelper.getJettyParameter("server.resource"));
        log.info(rootPath);

        Server server = new Server(Integer.parseInt(ConfigHelper.getJettyParameter("server.port")));
        WebAppContext webapp = new WebAppContext();
        webapp.setContextPath(ConfigHelper.getJettyParameter("server.name"));
        webapp.setResourceBase(rootPath);
        webapp.setDescriptor(rootPath + "/" + ConfigHelper.getJettyParameter("server.descriptor"));
        webapp.setParentLoaderPriority(true);
        webapp.setClassLoader(Thread.currentThread().getContextClassLoader());
        server.setHandler(webapp);
        try {
            log.info("===========================================================");
            log.info("[" + DateUtil.getDateTime() + "] CUMT-Restful is starting......");
            server.start();
            log.info("[" + DateUtil.getDateTime() + "] CUMT-Restful  has been started.");
            log.info("[" + DateUtil.getDateTime() + "] Please visit: http://127.0.0.1" + ":" + ConfigHelper.getJettyParameter("server.port") + ConfigHelper.getJettyParameter("server.name"));
            log.info("[" + DateUtil.getDateTime() + "] CUMT-Restful  Start successfully.");
            log.info("===========================================================");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
